<template>
  <el-dialog v-model="show" width="1100px" title="添加车辆型号" append-to-body :close-on-click-modal="false">
    <el-table v-loading="loading" :data="carList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" :selectable="selectable" />
      <el-table-column type="index" width="55" label="序号" align="center" />
      <el-table-column label="车辆图片" align="center" prop="photos" width="100">
        <template #default="scope">
          <el-image style="width: 40px;height: 40px" :src="scope.row.photos.split(',')[0]" :preview-src-list="scope.row.photos.split(',')" />
        </template>
      </el-table-column>
      <el-table-column label="车辆类型" min-width="100" align="center" prop="carType" />
      <el-table-column label="座位数" align="center" prop="carSeat" />
      <el-table-column label="车辆颜色" align="center" prop="carColor" />
      <el-table-column label="创建人" align="center" prop="createBy" />
      <el-table-column label="创建时间" align="center" prop="createTime" :show-overflow-tooltip="true" />
    </el-table>

    <template #footer>
      <div class="dialog-footer text-center">
        <el-button type="primary" @click="sure">确 定</el-button>
        <el-button @click="show=false">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>

import { getCurrentInstance, ref, watch } from 'vue'
import { addActivityCarBatch, listActivityCar } from '@/api/logex/activityCar'
import _ from 'lodash'
import { listCar } from '@/api/logex/car'


const emit = defineEmits(['complete'])
const { proxy } = getCurrentInstance()

let matchId = null
let rowId = null

const show = ref(false)
const carList = ref([])
const loading = ref(true)
const total = ref(0)
const ids = ref([])
const chooseCars = ref([])

watch(show, (val) => {
  if (!val) {
    carList.value = []
    total.value = 0
    ids.value = []
    matchId = null
    rowId = null
  }
})

function getList(receptionId) {
  loading.value = true
  listCar({
    vehicleId: receptionId,
    status: '1'
  }).then(res => {
    carList.value = res.rows
    loading.value = false
  })
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
}


function sure() {
  if (ids.value.length === 0) {
    proxy.$modal.msgWarning('请选择车辆')
    return
  }

  addActivityCarBatch({
    activityId: matchId,
    lavId: rowId,
    carIds: ids.value.join(',')
  }).then((res) => {
    proxy.$modal.msgSuccess(res.msg)
    show.value = false
    emit('complete', rowId)
  })
}

function selectable(row) {
  return !_.some(chooseCars.value, (r) => {
    return r.carId === row.id
  })
}

function open(params) {
  show.value = true
  matchId = params.matchId
  rowId = params.rowId

  getList(params.vehicleId)

  chooseCars.value = []
  listActivityCar({
    lavId: rowId
  }).then(res => {
    chooseCars.value = res.rows
  })
}
defineExpose({
  open
})

</script>

<style scoped>

</style>
